package com.edward.volleydemo;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonObjectRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;

/**
 * Created by Administrator on 2016/5/3.
 *
 * 自定义JsonObjectRequest ,解决乱码问题
 */
public class JsonObjectRequest_utf8 extends JsonObjectRequest {
    public JsonObjectRequest_utf8(int method, String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
        super(method, url, jsonRequest, listener, errorListener);
    }

    public JsonObjectRequest_utf8(String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
        super(url, jsonRequest, listener, errorListener);
    }


    //重写方法,修改编码集
    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
        try {

            //使用utf-8 转码
            String jsonString = new String(response.data, "utf-8");

            return Response.success(new JSONObject(jsonString), HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException e) {
            return Response.error(new ParseError(e));
        }
    }
}
